// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// l [author] rhyme_lph
// a [email]  rhymelph@gmail.com
// C [github] https://github.com/rhymelph

import 'dart:io';

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/a.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/provider/login/forgot_password_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:finance_app/src/widgets/button/normal_button.dart';
import 'package:finance_app/src/widgets/common/normal_error_text.dart';
import 'package:finance_app/src/widgets/input/input_field.dart';
import 'package:finance_app/src/widgets/input/phone_number_input_field.dart';
import 'package:finance_app/src/widgets/login/login_top_screen_widget.dart';
import 'package:finance_app/src/widgets/select/normal_radio.dart';
import 'package:finance_app/src/widgets/wrapper/normal_form_wrapper.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:pin_code_fields/pin_code_fields.dart';

@RouterMeta(paramName: "forgotPasswordPage")
class ForgotPasswordPage extends StatefulWidget {
  @override
  _ForgotPasswordPageState createState() => _ForgotPasswordPageState();
}

class _ForgotPasswordPageState extends State<ForgotPasswordPage>
    with PagePresenter<ForgotPasswordPage, ForgotPasswordProvider> {
  @override
  Widget get buildWidget => Scaffold(
        body: ListView(
          padding: EdgeInsets.zero,
          children: [
            _buildImageScreen(),
            AppSpaces.h35,
            listBuilder<String>(
                builder: (BuildContext context, String value, Widget child) =>
                    IndexedStack(
                      children: [
                        buildFirstScreen(),
                        buildSecondScreen(),
                      ],
                      index: value == null ? 0 : 1,
                    ),
                selector: (_, __) => __.number),
          ],
        ),
      );

  Widget buildFirstScreen() => Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          NormalFormWrapper(
            topPadding: getDp(22),
            bottomPadding: getDp(24),
            leftPadding: getDp(50),
            child: listBuilder<String>(
              selector: (_, __) => __.currentType,
              builder: (BuildContext context, String value, Widget child) =>
                  Row(
                children: [S.current.email, S.current.mobile_number]
                    .map(
                      (e) => PressedOpacityButton(
                        onPressed: () {
                          provider.onChangeType(e);
                        },
                        child: NormalRadio(
                          title: e,
                          isSelect: value == e,
                        ),
                      ),
                    )
                    .toList(),
              ),
            ),
          ),
          // _buildTipText(tip: S.current.enter_your_registered_mobile_number),
          // AppSpaces.h20,
          listBuilder<bool>(
              selector: (_, __) => __.currentType == S.current.email,
              builder: (BuildContext context, bool value, Widget child) => value
                  ? Column(
                      children: [
                        listBuilder<bool>(
                          selector: (_, __) => __.hasEmailError,
                          builder: (BuildContext context, bool value,
                                  Widget child) =>
                              InputField(
                            // leading: Icon(
                            //   Icons.email,
                            //   size: 15,
                            // ),
                            hint: S.current.email,
                            hasError: value,
                            focusNode: provider.emailFocus,
                            controller: provider.emailController,
                          ),
                        ),
                        listBuilder<bool>(
                          selector: (_, __) => __.hasEmailError,
                          builder: (BuildContext context, bool value,
                                  Widget child) =>
                              NormalErrorText(
                            content: 'Please enter a valid email address',
                            isVisibility: value,
                            margin: EdgeInsets.only(
                              left: getDp(45),
                              top: getDp(15),
                            ),
                          ),
                        ),
                      ],
                    )
                  : Column(
                      children: [
                        listBuilder<bool>(
                          selector: (_, __) => __.hasPhoneError,
                          builder: (BuildContext context, bool value,
                                  Widget child) =>
                              PhoneNumberInputField(
                            focusNode: provider.phoneFocus,
                            controller: provider.phoneController,
                            countryCodeCallback: provider.onChangeCountryCode,
                            hasError: value,
                          ),
                        ),
                        listBuilder<bool>(
                          selector: (_, __) => __.hasPhoneError,
                          builder: (BuildContext context, bool value,
                                  Widget child) =>
                              NormalErrorText(
                            content: S.current.please_enter_valid_phone_number,
                            isVisibility: value,
                            margin: EdgeInsets.only(
                              left: getDp(45),
                              top: getDp(15),
                            ),
                          ),
                        ),
                      ],
                    )),

          AppSpaces.h30,
          listBuilder<bool>(
              builder: (BuildContext context, bool value, Widget child) =>
                  NormalButton(
                    title: S.current.get_otp,
                    onTap: value == true ? provider.onGetOTP : null,
                  ),
              selector: (_, __) => __.enableGetOTP),
          AppSpaces.h30,
          Visibility(
              visible: (Platform.isAndroid &&
                      Config.settingApp.androidRegisterStatus == 1) ||
                  (Platform.isIOS && Config.settingApp.iosRegisterStatus == 1),
              child: Column(
                children: [
                  _buildOrDivider(),
                  AppSpaces.h26,
                  Center(
                    child: Text.rich(TextSpan(
                        text: S.current.not_have_account,
                        children: [
                          TextSpan(
                              text: S.current.register_here,
                              style: TextStyle(
                                color: aceBlueColor,
                                fontWeight: FontWeight.bold,
                              ),
                              recognizer: TapGestureRecognizer()
                                ..onTap = provider.onNavRegister)
                        ],
                        style: TextStyle(
                            fontSize: getSp(14),
                            color: aceDarkGrayColor,
                            fontWeight: FontWeight.w400,
                            fontFamily: "DinRoundPro"))),
                  ),
                ],
              )),
        ],
      );

  Widget buildSecondScreen() => Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          _buildTipText(
              tip: provider.currentType == S.current.email
                  ? 'Please enter the 6-digit OTP sent to\nyour email: ${provider.number}'
                  : S.current
                      .please_enter_tip(provider.countryCode, provider.number)),
          AppSpaces.h20,
          Padding(
            padding: EdgeInsets.symmetric(
              horizontal: getDp(52),
            ),
            child: listBuilder<bool>(
                builder: (BuildContext context, bool value, Widget child) =>
                    PinCodeTextField(
                      key: ValueKey("Forgot Password"),
                      controller: provider.validateController,
                      appContext: context,
                      textStyle: TextStyle(
                        color: aceBlackColor,
                        fontSize: getSp(16),
                        fontWeight: FontWeight.w400,
                        height: 22 / 16,
                      ),
                      pastedTextStyle: TextStyle(
                        color: aceBlackColor,
                        fontSize: getSp(16),
                        fontWeight: FontWeight.w400,
                        height: 22 / 16,
                      ),
                      length: 6,
                      animationType: AnimationType.fade,
                      pinTheme: PinTheme(
                          shape: PinCodeFieldShape.underline,
                          borderWidth: getDp(1),
                          selectedColor:
                              value == true ? aceRedColor : aceBlueColor,
                          activeColor:
                              value == true ? aceRedColor : aceBlueColor,
                          inactiveColor: aceGrayColor),
                      cursorColor: aceBlueColor,
                      animationDuration: Duration(milliseconds: 300),
                      // enableActiveFill: true,
                      // errorAnimationController: errorController,
                      // controller: textEditingController,
                      keyboardType: TextInputType.number,
                      onCompleted: (v) {},
                      beforeTextPaste: (text) {
                        return true;
                      },
                      onChanged: (String value) {},
                    ),
                selector: (_, __) => __.hasValidateError),
          ),
          _buildInputValidateTip(),
          AppSpaces.h30,
          listBuilder<bool>(
              builder: (BuildContext context, bool value, Widget child) =>
                  NormalButton(
                    title: S.current.verify,
                    onTap: value == true ? provider.onVerify : null,
                  ),
              selector: (_, __) => __.enableVerify),
          AppSpaces.h20,
          Center(
            child: Text.rich(TextSpan(
                text: S.current.did_not_receive_the_otp,
                children: [
                  TextSpan(
                      text: S.current.resend_otp,
                      style: TextStyle(
                        color: aceBlueColor,
                        fontWeight: FontWeight.bold,
                      ),
                      recognizer: TapGestureRecognizer()
                        ..onTap = provider.onResentOTP)
                ],
                style: TextStyle(
                    fontSize: getSp(14),
                    color: aceDarkGrayColor,
                    fontWeight: FontWeight.w400,
                    fontFamily: "DinRoundPro"))),
          )
        ],
      );

  Center _buildInputValidateTip() {
    return Center(
      child: listBuilder<int>(
          builder: (BuildContext context, int expire, Widget child) =>
              listBuilder<bool>(
                  builder: (BuildContext context, bool value, Widget child) =>
                      Text(
                        value == true
                            ? 'You have entered the wrong OTP'
                            : expire == 0
                                ? 'Your OTP has expired. Please select resend OTP'
                                : S.current.otp_expires_in_time(
                                    DateFormat('mm:ss').format(
                                        DateTime(0, 0, 0, 0, 0)
                                            .add(Duration(seconds: expire)))),
                        style: TextStyle(
                          color: value == true ? aceRedColor : aceDarkGrayColor,
                          fontSize: getSp(12),
                          fontWeight: FontWeight.w400,
                          height: 16 / 12,
                        ),
                      ),
                  selector: (_, __) => __.hasValidateError),
          selector: (_, __) => __.currentOTPExpireTimer),
    );
  }

  Widget _buildImageScreen() => LoginTopScreenWidget(
        imagePath: A.assetsImagesGraphicForgotPassword,
        imageName: S.current.forgot__password,
      );

  Widget _buildOrDivider() => Container(
        margin: EdgeInsets.symmetric(
          horizontal: getDp(43),
        ),
        child: Row(
          children: [
            Expanded(
                child: Container(
              height: getDp(1),
              color: aceGrayColor,
            )),
            Padding(
              padding: EdgeInsets.symmetric(horizontal: getDp(14)),
              child: Text(
                S.current.or,
                style: TextStyle(
                  color: aceGrayColor,
                  fontSize: getSp(14),
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            Expanded(
                child: Container(
              height: getDp(1),
              color: aceGrayColor,
            )),
          ],
        ),
      );

  Center _buildTipText({String tip}) {
    return Center(
      child: Text(
        tip,
        style: TextStyle(
          color: aceBlackColor,
          fontSize: getSp(16),
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }
}
